package com.shuqing.download.engine;

import com.shuqing.download.engine.config.EngineConfig;
import com.shuqing.download.engine.data.DataFillHandler;
import com.shuqing.download.engine.distribute.DistributeHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 下载处理引擎
 * @author wangshuqing
 * @date 2023/2/12 14:32
 */
@Slf4j
@Component
public class DownLoadEngine {

    @Autowired
    private EngineConfig engineConfig;
    @Autowired
    private DataFillHandler fillHandler;
    @Autowired
    private DistributeHandler distributeHandler;
    /**添加参数，反正启动被多次调用**/
    private boolean isStart=false;
    /**
    * 启动下载任务
     * 利用默认线程池异步处理
    * @date 2023/2/12 14:34
    * @author wangshuqing
    * @param
    * */
    @Async
    @SneakyThrows
    public void start(){
        if(isStart){
            return ;
        }
        isStart=true;
        init();
        while (true){
            boolean needSleep=false;
            //获取分发器认可
            boolean accept=distributeHandler.accept();
            if(accept){
                //取数据
                DownLoadTaskDto task=fillHandler.nextData();
                if(task==null){
                    //如果没有数据,就休眠,等待数据填充
                    distributeHandler.backOneAccept();
                    needSleep=true;
                }else{
                    //分发数据
                    distributeHandler.process(task);
                    needSleep=false;
                }
            }
            if(needSleep){
                //间隙休眠
                log.info("没有任务开始休眠一会{}",engineConfig.getGapSleepTills());
                Thread.sleep(engineConfig.getGapSleepTills());
            }
        }
    }

    private void init(){
        log.info("初始化下载任务引擎...");
    }

    /**
    * 每30s执行一次* 为redis 补数据
    * @date 2023/2/12 18:34
    * @author wangshuqing
    * @param
    * */
    @Scheduled(cron = "0/31 * * * * ?")
    public void supplement(){
        fillHandler.supplement();
    }


    /**
    * 一次拉取多条数据 进行处理
     *可以配置定时: @Scheduled(initialDelay=55000, fixedRate=2000)
    * @date 2023/2/25 13:42
    * @author wangshuqing
    * @param
    * */
    public void startByScheduled(){
        int count=distributeHandler.possibleMoreAccept();
        if(count>0){
            for(int i=0;i<count;i++){
                DownLoadTaskDto task=fillHandler.nextData();
                if(task==null){
                    distributeHandler.backOneAccept();
                }else{
                    distributeHandler.process(task);
                }
            }
        }
    }

    /**
    * 定期清理临时文件 本地测试环境暂不开启
    * @date 2023/2/24 23:54
    * @author wangshuqing
    * @param
    * */
    //@Scheduled(initialDelay=55000, fixedRate=5*60*60*1000)
    public void clearTempFile(){
        log.info("开始清理临时文件");
        File file=new File(engineConfig.getExportFileSavePath());
        long now=System.currentTimeMillis()-engineConfig.getClearTempTimes();
        clearFile(file,now);
        log.info("结束清理临时文件");
    }

    private void clearFile(File file,long now){
        if(file.exists()){
            File[] subFiles=file.listFiles();
            if(subFiles!=null && subFiles.length>0){
                for(File subFile:subFiles){
                    if(subFile.isDirectory()){
                        if(now>subFile.lastModified()){
                            log.info("清理文件{}",subFile.getAbsolutePath());
                            subFile.delete();
                        }
                    }else{
                        clearFile(subFile,now);
                    }
                }
            }else{
                log.info("清理文件夹{}",file.getAbsolutePath());
                file.delete();
            }
        }
    }

}
